package code;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

// 新闻数据类
class News {
    private long nid;
    private String title;

    public News(long nid, String title) {
        this.nid = nid;
        this.title = title;
    }

    @Override
    public String toString() {
        return "【新闻数据】新闻编号：" + this.nid + "、新闻标题：" + this.title;
    }
}

// 自定义延迟缓存类（补充缺失的Cache类）
class Cache<K, V> {
    private final ConcurrentHashMap<K, V> cacheMap = new ConcurrentHashMap<>();
    private final DelayQueue<DelayItem<K>> delayQueue = new DelayQueue<>();
    private final long delaySeconds = 5; // 缓存过期时间

    public Cache() {
        // 后台线程自动清理过期缓存
        new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    DelayItem<K> expired = delayQueue.take();
                    cacheMap.remove(expired.getKey());
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }).start();
    }

    public void put(K key, V value) {
        cacheMap.put(key, value);
        long expireTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(delaySeconds);
        delayQueue.put(new DelayItem<>(key, expireTime));
    }

    public V get(K key) {
        return cacheMap.get(key);
    }

    // 延迟队列元素类
    static class DelayItem<K> implements Delayed {
        private final K key;
        private final long expireTime;

        public DelayItem(K key, long expireTime) {
            this.key = key;
            this.expireTime = expireTime;
        }

        public K getKey() {
            return key;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(expireTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            return Long.compare(this.expireTime, ((DelayItem<?>) o).expireTime);
        }
    }
}

// 主类（修正命名规范）
public class yootkdemo9 {
    public static void main(String[] args) throws Exception {
        Cache<Long, News> cache = new Cache<>();
        // 修正构造函数调用（去掉命名参数）
        cache.put(1L, new News(1L, "沐言科技：www.yootk.com"));
        cache.put(2L, new News(2L, "李兴华高薪就业编程训练营：edu.yootk.com"));

        System.out.println(cache.get(1L));
        System.out.println(cache.get(2L));

        TimeUnit.SECONDS.sleep(5);
        System.out.println("------------------- 5秒之后再次读取数据 -------------------");
        System.out.println(cache.get(1L));
    }
}